package com.lancoo.znbkxx.teacher.base

import android.content.Intent
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.os.IBinder
import android.view.*
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import android.widget.FrameLayout
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.ViewModelProvider
import com.android.tu.loadingdialog.LoadingDialog
import com.lancoo.znbkxx.teacher.utils.ButtonUtils
import me.jessyan.autosize.internal.CustomAdapt

/**
 * @author : Admin
 * @date   : 2019/7/12 21:37
 * @desc   :
 */
abstract class BaseVMActivity<VM : BaseViewModel, DB : ViewDataBinding> : AppCompatActivity(),
        CustomAdapt {
    val loadingDialog by lazy {
        LoadingDialog.Builder(this).setMessage("加载中...").setCancelable(true)
                .setCancelOutside(true).create()
    }
    lateinit var viewModel: VM
    lateinit var binding: DB
    override fun onCreate(savedInstanceState: Bundle?) {
        fullScreen(false)
        initVM()
        binding = DataBindingUtil.setContentView(this, setLayoutID())
        initView()
        binding.lifecycleOwner = this
        initData()
        startObserve()

        SharedPreferencesHelper.init(this, "LancooListenClass")
        val isHealtheye = SharedPreferencesHelper.getBoolean("teahealtheye", false)
        if (isHealtheye) {
            openAleterWindow()
        } else {
            closeHealthEye()
        }
        super.onCreate(savedInstanceState)
    }

    abstract fun setLayoutID(): Int
    abstract fun initView()
    open fun initData() {}
    private fun initVM() {
        providerVMClass()?.let {
            viewModel = ViewModelProvider(this).get(it)
            lifecycle.addObserver(viewModel)
        }
    }

    open fun startObserve() {}

    open fun providerVMClass(): Class<VM>? = null

    override fun onDestroy() {
        lifecycle.removeObserver(viewModel)
        super.onDestroy()
    }

    protected fun startActivity(z: Class<*>) {
        startActivity(Intent(this, z))
    }

    protected fun startActivity(z: Class<*>, name: String, value: Boolean) {
        val intent = Intent(this, z).putExtra(name, value)
        startActivity(intent)
        //todo
    }

    override fun isBaseOnWidth(): Boolean {
        return false
    }

    override fun getSizeInDp(): Float {
        return 667f
    }

    fun fullScreen(dark: Boolean) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            val decorView = window.decorView
            if (dark) {
                decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
            } else {
                decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
            }
            window.statusBarColor = Color.TRANSPARENT
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
        } else {
            val attributes = window.attributes
            val flagTranslucentStatus = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
            attributes.flags = attributes.flags or flagTranslucentStatus
            window.attributes = attributes
        }
    }

    /**
     * 重写点击事件
     * @param ev
     * @return
     */
    override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
        if (ev.action == MotionEvent.ACTION_DOWN) {
            //防止短时间内多次点击
            if (ButtonUtils.isFastDoubleClick) {
                return true
            }
            //实现软键盘点击空白处自动回收
            val v = currentFocus //得到当前页面的焦点,ps:有输入框的页面焦点一般会被输入框占据
            if (isShouldHideKeyboard(v, ev)) { //判断用户点击的是否是输入框以外的区域
                hideKeyboard(v!!.windowToken) //收起键盘
            }
        }
        return super.dispatchTouchEvent(ev)
    }

    /**
     * 根据EditText所在坐标和用户点击的坐标相对比，来判断是否隐藏键盘，因为当用户点击EditText时则不能隐藏
     * @param v
     * @param event
     * @return
     */
    open fun isShouldHideKeyboard(v: View?, event: MotionEvent): Boolean {
        if (v != null && v is EditText) {  //判断得到的焦点控件是否包含EditText
            val l = intArrayOf(0, 0)
            v.getLocationInWindow(l)
            val left = l[0]
            //得到输入框在屏幕中上下左右的位置
            val top = l[1]
            val bottom: Int = top + v.getHeight()
            val right: Int = left + v.getWidth()
            return !(event.x > left && event.x < right && event.y > top && event.y < bottom)
        }
        // 如果焦点不是EditText则忽略
        return false
    }

    /**
     * 获取InputMethodManager，隐藏软键盘
     * @param token
     */
    open fun hideKeyboard(token: IBinder?) {
        if (token != null) {
            val im: InputMethodManager = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
            im.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS)
        }
    }

    private var frameLayout: FrameLayout? = null
    private fun openAleterWindow() {   //打开 dailog 窗口 对 dailog 初始化

        val decorView = this.window.decorView as ViewGroup
        frameLayout = FrameLayout(applicationContext)
        val params = ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT
        )
        decorView.addView(frameLayout, params)
        getData()
    }

    private fun closeHealthEye() {
        val decorView = this.window.decorView as ViewGroup
        decorView.removeView(frameLayout)
    }


    fun getData() {  //获取 存储 sharePrefrence 保存的三原色值
        val realFilter = 20
        val a = (realFilter / 80f * 180).toInt()
        val r = (200 - realFilter / 80f * 190).toInt()
        val g = (180 - realFilter / 80f * 170).toInt()
        val b = (60 - realFilter / 80f * 60).toInt()
        frameLayout!!.setBackgroundColor(Color.argb(a, r, g, b))
    }

    fun showAnimation() {
        val lp = window.attributes
        lp.alpha = 0.8f
        window.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND)
        window.attributes = lp
    }

    fun dismissAnimation() {
        val lp = window.attributes
        lp.alpha = 1.0f
        window.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND)
        window.attributes = lp
    }
}